import { clearStorageSync, getStorageSync, toast, useRouter } from '@/utils'
import RequestManager from './requestManager.js'

const BASE_URL = import.meta.env.VITE_APP_URL
const manager = new RequestManager()

const baseRequest = async (url, method, data = {}, loading = true) => {
  let requestId = manager.generateId(method, url, data)
  if (!requestId) {
    console.log('重复请求')
  }
  if (!requestId) return false

  const header = {}
  header.token = getStorageSync('token') || ''

  return new Promise((resolve, reject) => {
    if (loading) {
      uni.showLoading({ title: 'loading' })
    }
    uni.request({
      url: BASE_URL + url,
      method: method || 'GET',
      header,
      timeout: 10000,
      data: data || {},
      complete: () => {
        manager.deleteById(requestId)
      },
      success: (res) => {
        console.log(res, 'res有什么')
        if (res.data.code === 200) {
          // if (import.meta.env.VITE_ENCIPHER === 'true') {
          //   let key = decryptReqList[res.config.headers.sign].key
          //   let iv = decryptReqList[res.config.headers.sign].iv
          //   res.data.data = res.data.data ? Decrypt(res.data.data, key, iv) : res.data.data
          // }
          // console.log(res.data, res.config.url)
          // return res.data
        } else if (res.data.code === 40103) { // 账号在其他地方登录
          toast(res.data.msg)
          setTimeout(() => {
            clearStorageSync()
            useRouter('/pages/login/index', 'reLaunch')
          }, 1000)
        } else {
          toast(res.data.msg)
          reject(res)
        }
        resolve(res.data)
      },
      fail: (msg) => {
        console.log(msg, '失败了')
        toast('网络连接失败，请稍后重试')
        reject(msg)
      }
    })
  }).finally(() => {
    uni.hideLoading()
  })
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})

export default request
